package asionreachel.cn.smarthomedemo.base;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.widget.EditText;
import android.widget.Toast;

import java.io.UnsupportedEncodingException;
import java.util.regex.Pattern;

import asionreachel.cn.smarthomedemo.activity.DialogLoading;
import asionreachel.cn.smarthomedemo.activity.EditTextInfoActivity;
import asionreachel.cn.smarthomedemo.activity.PersonalCenterActivify;
import asionreachel.cn.smarthomedemo.activity.SelectDeviceActivity;
import asionreachel.cn.smarthomedemo.activity.SelectModeActivity;
import asionreachel.cn.smarthomedemo.thread.JFamilyClientApp;
import familyclient.java.common.error.JError;
import nccore.java.data.JNCError;

import static android.content.Context.MODE_PRIVATE;

/**
 * Created by SuperMa on 2017/5/8.
 */

public class Common {
    private static String TAG = "Common";
    public static boolean s_bDirectConnect = false;
    public static String s_strFamilyID = "";
    public static String s_strOperateID = "GSLL";
    public static String s_strOperatePwd = "GSLL001";
    private static SharedPreferences m_sharedPreferences = null;
    private static SharedPreferences.Editor m_editor = null;
    private static Toast mToast;
    public static Dialog mDiaLogLoading;
    private static String currentString = "";

    public static Class getMainClass()
    {
        return SelectDeviceActivity.class;
    }

    public static void initSharedPreferences()
    {
        if(m_sharedPreferences == null)
        {
            m_sharedPreferences = JFamilyClientApp.getInstance().getApplicationContext().getSharedPreferences("app_info" , MODE_PRIVATE);
            m_editor = m_sharedPreferences.edit();
        }
    }

    public static SharedPreferences getAppSharedPreferences()
    {
        return m_sharedPreferences;
    }

    public static SharedPreferences.Editor getAppEditor()
    {
        return m_editor;
    }

    //校验邮箱地址
    public static boolean checkEmail(String email)
    {
        if (isNotEmpty(email, true) == false) {
            return false;
        }

        String str = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
        Pattern p = Pattern.compile(str);

        currentString = email;

        return p.matcher(email).matches();
    }

    //校验手机号码
    public static boolean checkPhoneNumber(String a_strPhone)
    {
        //现有手机号段:
        //移动：139   138   137   136   135   134   147   150   151   152   157   158    159   178  182   183   184   187   188
        //联通：130   131   132   155   156   185   186   145   176
        //电信：133   153   177   173   180   181   189
        //虚拟运营商：170  171
        //整理后：130~139  145,147 15[012356789] 178,176,177,173,170,171 180~189
//        boolean bFlag = true;
//        String regExp = "^0?(13[0-9]|15[012356789]|17[013678]|18[0-9]|14[57])[0-9]{8}$";
//        Pattern p = Pattern.compile(regExp);
//        Matcher m = p.matcher(a_strPhone);
//        bFlag = m.find();//boolean
//        return bFlag;
        if (isNotEmpty(a_strPhone, true) == false) {
            return false;
        }

        Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0-2,5-9])|(17[0-9]))\\d{8}$");

        currentString = a_strPhone;

        return p.matcher(a_strPhone).matches();
    }

    //校验验证码
    public static boolean checkVerifyCode(String a_strVerifyCode)
    {
        if(TextUtils.isEmpty(a_strVerifyCode))
        {
            return false;
        }
        return true;
    }

    //保存登录账号id
    public static void saveAccountId(String _accountId)
    {
        m_editor.putString( EncryptUtil.getInstance().encrypt( ConstantDefinition.LOGIN_ACCOUNTID ), EncryptUtil.getInstance().encrypt( _accountId ) );
        m_editor.commit();
    }

    //保存密码
    public static void savePassword(String _password)
    {
        m_editor.putString( EncryptUtil.getInstance().encrypt( ConstantDefinition.LOGIN_PASSWORD), EncryptUtil.getInstance().encrypt( _password ) );
        m_editor.commit();
    }

    //保存账号信息
    public static void saveClientAccount(String a_strAccountId , String a_strPassword)
    {
        saveAccountId(a_strAccountId);
        savePassword(a_strPassword);
    }

    public static void saveDeviceIDWithTag( String a_strTag, String a_strDeviceID )
    {
        m_editor.putString( a_strTag, a_strDeviceID );
        m_editor.commit();
    }


    public static String getDeviceIDWithTag( String a_strTag )
    {
        String strDeviceID = m_sharedPreferences.getString( a_strTag, "");
        return strDeviceID;
    }

    public static boolean getPasswordHide()
    {
        boolean isShow =  m_sharedPreferences.getBoolean(ConstantDefinition.LOGIN_PASSWORD_HIDE , true);
        return isShow;
    }

    public static void savePasswordHide(boolean b_check)
    {
        m_editor.putBoolean(ConstantDefinition.LOGIN_PASSWORD_HIDE , b_check);
        m_editor.commit();
    }

    public static String getAccountId()
    {
        String accountId = m_sharedPreferences.getString( EncryptUtil.getInstance().encrypt( ConstantDefinition.LOGIN_ACCOUNTID ), "");
        return EncryptUtil.getInstance().decrypt( accountId );
    }

    public static String getPassword()
    {
        String password = m_sharedPreferences.getString( EncryptUtil.getInstance().encrypt( ConstantDefinition.LOGIN_PASSWORD ), "");
        return EncryptUtil.getInstance().decrypt( password );
    }

    public synchronized static void showToast(String a_strMsg) {
        if (mToast == null) {
            mToast = Toast.makeText(JFamilyClientApp.getInstance().getApplicationContext(), a_strMsg, Toast.LENGTH_SHORT);
        } else {
            synchronized (mToast) {
                mToast.setText(a_strMsg);
                mToast.setDuration(Toast.LENGTH_SHORT);
            }
        }
        mToast.show();
    }

    public synchronized static void showToast(int a_iMsg)
    {
        String a_strMsg = JFamilyClientApp.getInstance().getApplicationContext().getString(a_iMsg);
        showToast(a_strMsg);
    }

    public static void saveWifiPassword(String a_strWifiName , String a_strPassword)
    {
        m_editor.putString(a_strWifiName , a_strPassword);
        m_editor.commit();
    }

    public static String getWifiPassword(String a_strWifiName)
    {
        return m_sharedPreferences.getString(a_strWifiName , "");
    }

    /** 获取wifi名 */
    public static String getWifiName() {
        if(!isWifiConnected(JFamilyClientApp.getInstance().getApplicationContext())){
            Common.showToast("请连接WiFi");
            return "";
        }
        WifiManager wifiMgr = (WifiManager) JFamilyClientApp.getInstance().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        int wifiState = wifiMgr.getWifiState();
        WifiInfo info = wifiMgr.getConnectionInfo();
        String wifiId = info != null ? info.getSSID().toString() : "";
        return wifiId.replaceAll("\"", "");
    }

    public static String getWifiBSSID() {
        if(!isWifiConnected(JFamilyClientApp.getInstance().getApplicationContext())){
            Common.showToast("请连接WiFi");
            return "";
        }
        WifiManager wifiMgr = (WifiManager)JFamilyClientApp.getInstance().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        WifiInfo info = wifiMgr.getConnectionInfo();
        String wifiId = info != null ? info.getBSSID() : "";
        return wifiId.replaceAll("\"", "");
    }

    //是否连接WIFI
    public static boolean isWifiConnected(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo wifiNetworkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if(wifiNetworkInfo.isConnected()) {
            return true ;
        }
        return false ;
    }

    public static boolean getRememberPassword()
    {
        boolean bRemember = m_sharedPreferences.getBoolean(ConstantDefinition.LOGIN_PASSWORD_REMENBER , true);
        return bRemember;
    }

//    打开个人中心
    public static void openPersonalCenter(Activity _tp)
    {

//        Intent intent = new Intent(_tp,ForgotPasswordActivity.class);
//        _tp.startActivity(intent);
//        showToast("demo无法查看");
        Intent intent = new Intent(_tp , PersonalCenterActivify.class);
        _tp.startActivity(intent);
    }

    //添加设备
    public static void openAddDevice(Activity _tp)
    {
        Intent intent = new Intent(_tp , SelectModeActivity.class);
        _tp.startActivity(intent);
    }
    public static void openEditTextInfoActivity(Activity _tp , int a_iResultCode , String a_strParm , String a_strContent , int a_iMaxEms , String a_strTitle)
    {
        Intent intent = new Intent(_tp , EditTextInfoActivity.class);
        intent.putExtra(ConstantDefinition.EDIT_PARM , a_strParm);
        intent.putExtra(ConstantDefinition.EDIT_CONTENT , a_strContent);
        intent.putExtra(ConstantDefinition.EDIT_RESULT_CODE , a_iResultCode);
        intent.putExtra(ConstantDefinition.EDIT_TITLE , a_strTitle);
        if (a_iMaxEms > 0)
            intent.putExtra(ConstantDefinition.EDIT_MAX_EMS , a_iMaxEms);
        _tp.startActivity(intent);
        EditTextInfoActivity.setEditItemClickListener(null);
    }

    public static void showDialogLoading(Activity _tp ,String a_strMsg)
    {
        if (mDiaLogLoading != null)
            DialogLoading.closeDialog(mDiaLogLoading);
        mDiaLogLoading = DialogLoading.createLoadingDialog(_tp , a_strMsg);
        //需要一个定时器，定时关闭dialog,最长连接
    }

    public static void setDialogLoadingMsg( String a_strMsg )
    {
        if( mDiaLogLoading != null ) {
            DialogLoading.closeDialog(mDiaLogLoading);
            mDiaLogLoading = DialogLoading.createLoadingDialog( mDiaLogLoading.getContext(), a_strMsg);
        }
    }

    public static void closeDialogLoading()
    {
        DialogLoading.closeDialog(mDiaLogLoading);
        mDiaLogLoading = null;
    }

    /**判断字符是否非空
     * @param s
     * @param trim
     * @return
     */
    public static boolean isNotEmpty(String s, boolean trim) {
        //		Log.i(TAG, "getTrimedString   s = " + s);
        if (s == null) {
            return false;
        }
        if (trim) {
            s = s.trim();
        }
        if (s.length() <= 0) {
            return false;
        }
        currentString = s;
        return true;
    }
    /**获取刚传入处理后的string
     * @must 上个影响currentString的方法 和 这个方法都应该在同一线程中，否则返回值可能不对
     * @return
     */
    public static String getCurrentString() {
        return currentString == null ? "" : currentString;
    }

    public static String AnalysisScanCode( String a_strScanCode, String a_strKey ) {
        if( null == a_strScanCode || 0 == a_strScanCode.length() )
            return "";

        String[] arrStrItem = a_strScanCode.split( ";" );
        for( int iIndex = 0 ; iIndex < arrStrItem.length ; ++iIndex ) {
            String[] arrStr = arrStrItem[iIndex].split( ":" );
            if( 2 != arrStr.length )
                continue;

            if( arrStr[0].equals( a_strKey ) )
                return arrStr[1];
        }
        return "";
    }

    public static String MakeMsgByErr( String a_strFunction ,String a_strErr )
    {
        String[][] arrErrToMsg = {
                { JNCError.s_strErrUnknow, "未知错误" },
                { JNCError.s_strErrParamIllegal, "参数错误" },
                { JNCError.s_strErrVmpIllegal, "参数错误" },
                { JNCError.s_strErrNoProc, "请求被拒绝" },
                { JNCError.s_strErrObjNotExist, "请求被拒绝" },
                { JNCError.s_strErrCommunicationException, "通信异常" },
                { JNCError.s_strErrTimeOut, "请求超时" },

                { JError.s_strErrIDOrPwdWrong, "账号或密码错误" },
                { JError.s_strErrVerCodeWrong, "验证码错误" },
                { JError.s_strErrDBLPhone, "手机号已存在" },
                { JError.s_strErrDBLEmail, "邮箱已存在" },
                { JError.s_strErrUnSupportVehicle, "不支持的账号或邮箱" },
                { JError.s_strErrOffline, "设备不在线" },
                { JError.s_strErrForbidden, "不允许操作" },
                { JError.s_strErrTooFrequently, "操作太频繁" }
        };

        for( int iIndex = 0 ; iIndex < arrErrToMsg.length ; ++iIndex )
        {
            if( arrErrToMsg[iIndex][0].equals( a_strErr ) ){
                return arrErrToMsg[iIndex][1];
            }
        }

        return "未知错误";
    }

    //更新密码是否明文显示
    public static void setEditTextStyle(EditText et_pw, boolean b_check)
    {
        if (b_check)
        {
            et_pw.setTransformationMethod(HideReturnsTransformationMethod.getInstance());  //密码以明文显示
        }
        else
        {
            et_pw.setTransformationMethod(PasswordTransformationMethod.getInstance());  //以密文显示，以.代替
        }
    }

    public static String subString(String s, int length) throws UnsupportedEncodingException {
        int subLength = 0;
        for(int i = 0; i < s.length(); i++)
        {
            int ascii = Character.codePointAt(s, i);
            if(ascii >= 0 && ascii <=255)
            {
                subLength++;
            }
            else
            {
                subLength += 2;
            }
            if (subLength > length)
                return s.substring(0 , i);
        }
        return s;
    }

    public static int getWordCount(String s)
    {
        int length = 0;
        for(int i = 0; i < s.length(); i++)
        {
            int ascii = Character.codePointAt(s, i);
            if(ascii >= 0 && ascii <=255)
                length++;
            else
                length += 2;
        }
        return length;

    }
}
